#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 文件名称: query_api.py
# 文件保存路径: backend/api/miniprogram/query_api.py
"""
微信小程序数据查询API
实现学生信息、视力数据、干预记录等查询功能
"""

from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy import desc
from backend.infrastructure.database import db
from backend.models.user import User
from backend.models.student import Student, StudentExtension
from backend.models.vision import VisionRecord
from backend.models.intervention import InterventionRecord
from backend.api.miniprogram import miniprogram_bp
from backend.services.unified_log_service import UnifiedLogService
from backend.infrastructure.database import db
from sqlalchemy import and_

@miniprogram_bp.route('/query/student', methods=['GET'])
@jwt_required()
def get_student_info():
    """
    获取学生基本信息
    """
    try:
        current_user_id = get_jwt_identity()
        # JWT identity是字符串，需要转换为整数
        user = User.query.get(int(current_user_id))
        
        if not user or not user.student_id:
            return jsonify({
                'success': False,
                'message': '用户未绑定学生'
            }), 400
        
        student = Student.query.get(user.student_id)
        if not student:
            return jsonify({
                'success': False,
                'message': '学生信息不存在'
            }), 404
        
        # 获取最新的年度扩展信息
        latest_extension = StudentExtension.query.filter_by(
            student_id=student.id
        ).order_by(desc(StudentExtension.data_year)).first()
        
        student_data = {
            'id': student.id,
            'name': student.name,
            'education_id': student.education_id,
            'school': student.school,
            'class_name': student.class_name,
            'gender': student.gender,
            'birthday': student.birthday.isoformat() if student.birthday else None,
            'id_card': student.id_card,
            'parent_name': student.parent_name,
            'parent_phone': student.parent_phone,
            'contact_address': student.contact_address
        }
        
        # 添加年度扩展信息
        if latest_extension:
            student_data['extension'] = {
                'data_year': latest_extension.data_year,
                'grade': latest_extension.grade,
                'age': latest_extension.age,
                'height': latest_extension.height,
                'weight': latest_extension.weight,
                'past_history': latest_extension.past_history,
                'family_history': latest_extension.family_history
            }
        
        return jsonify({
            'success': True,
            'data': student_data,
            'message': '获取学生信息成功'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取学生信息失败: {str(e)}'
        }), 500

@miniprogram_bp.route('/query/vision', methods=['GET'])
@jwt_required()
def get_vision_records():
    """
    获取视力记录数据
    """
    try:
        current_user_id = get_jwt_identity()
        # JWT identity是字符串，需要转换为整数
        user = User.query.get(int(current_user_id))
        
        if not user or not user.student_id:
            return jsonify({
                'success': False,
                'message': '用户未绑定学生'
            }), 400
        
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        year = request.args.get('year', type=str)
        
        # 构建查询
        query = VisionRecord.query.filter_by(student_id=user.student_id)
        
        if year:
            query = query.filter(VisionRecord.data_year == year)
        
        # 按测量日期倒序排列
        query = query.order_by(desc(VisionRecord.measure_date))
        
        # 分页
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        records = []
        for record in pagination.items:
            record_data = {
                'id': record.id,
                'measure_date': record.measure_date.isoformat() if record.measure_date else None,
                'data_year': record.data_year,
                'measurement_sequence': record.measurement_sequence,
                'is_baseline': record.is_baseline,
                'left_eye_naked': record.left_eye_naked,
                'right_eye_naked': record.right_eye_naked,
                'left_eye_corrected': record.left_eye_corrected,
                'right_eye_corrected': record.right_eye_corrected,
                'left_sphere': record.left_sphere,
                'right_sphere': record.right_sphere,
                'left_cylinder': record.left_cylinder,
                'right_cylinder': record.right_cylinder,
                'left_axis': record.left_axis,
                'right_axis': record.right_axis,
                'left_se': record.left_se,
                'right_se': record.right_se,
                'vision_level': record.vision_level,
                'myopia_degree': record.myopia_degree,
                'remarks': record.remarks
            }
            records.append(record_data)
        
        return jsonify({
            'success': True,
            'data': {
                'records': records,
                'pagination': {
                    'page': page,
                    'per_page': per_page,
                    'total': pagination.total,
                    'pages': pagination.pages,
                    'has_next': pagination.has_next,
                    'has_prev': pagination.has_prev
                }
            },
            'message': '获取视力记录成功'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取视力记录失败: {str(e)}'
        }), 500

@miniprogram_bp.route('/vision/<int:record_id>', methods=['GET'])
@jwt_required()
def get_vision_detail(record_id: int):
    """获取单条视力记录详情 (面向小程序详情页)

    设计说明:
    1. 仅允许访问当前登录用户绑定学生的记录; 其它学生记录返回 404 避免信息泄露。
    2. 返回字段使用 VisionRecord.to_dict() 完整集合，前端可按需展示。
    3. 与干预详情接口 (/intervention/<id>) 风格保持一致: { success, data, message }。
    4. 若未绑定学生 => 400, 若记录不存在 => 404。
    """
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(int(current_user_id))
        if not user or not user.student_id:
            return jsonify({'success': False, 'message': '用户未绑定学生'}), 400
        vr = VisionRecord.query.filter(and_(VisionRecord.id == record_id, VisionRecord.student_id == user.student_id)).first()
        if not vr:
            return jsonify({'success': False, 'message': '视力记录不存在'}), 404
        return jsonify({'success': True, 'data': vr.to_dict(), 'message': '获取视力记录成功'})
    except Exception as e:  # noqa: BLE001
        return jsonify({'success': False, 'message': f'获取视力记录失败: {str(e)}'}), 500

@miniprogram_bp.route('/query/intervention', methods=['GET'])
@jwt_required()
def get_intervention_records():
    """
    获取干预记录数据
    """
    try:
        current_user_id = get_jwt_identity()
        # JWT identity是字符串，需要转换为整数
        user = User.query.get(int(current_user_id))
        
        if not user or not user.student_id:
            return jsonify({
                'success': False,
                'message': '用户未绑定学生'
            }), 400
        
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        intervention_type = request.args.get('intervention_type', type=str)
        is_home = request.args.get('is_home', type=str)
        
        # 构建查询
        query = InterventionRecord.query.filter_by(student_id=user.student_id)
        
        # 调试信息
        print(f"查询干预记录 - 学生ID: {user.student_id}")
        total_count = query.count()
        print(f"找到干预记录总数: {total_count}")
        
        if intervention_type:
            query = query.filter(InterventionRecord.intervention_type == intervention_type)
        
        if is_home:
            is_home_bool = is_home.lower() == 'true'
            query = query.filter(InterventionRecord.is_home_intervention == is_home_bool)
        
        # 按干预日期倒序排列
        query = query.order_by(desc(InterventionRecord.intervention_date))
        
        # 分页
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        records = []
        for record in pagination.items:
            display_operator = record.operator or (record.home_operator if record.is_home_intervention else None)
            # 仅使用主字段；若为空（理论上不该为空），提供一个安全回退
            record_type = record.intervention_type or '未指定'
            record_data = {
                'id': record.id,
                'intervention_date': record.intervention_date.isoformat() if record.intervention_date else None,
                'intervention_type': record_type,
                'operator': display_operator,
                'duration_minutes': record.duration_minutes,
                'is_home_intervention': record.is_home_intervention,
                'home_operator': record.home_operator,
                'home_operator_relation': record.home_operator_relation,
                'home_intervention_day': record.home_intervention_day,
                'daily_frequency': record.daily_frequency,
                'parent_feedback': record.parent_feedback,
                'upload_source': record.upload_source,
                'child_cooperation': record.child_cooperation,
                'daily_effect_rating': record.daily_effect_rating,
                'details': record.details,
                'created_at': record.created_at.isoformat() if record.created_at else None
            }
            records.append(record_data)
        
        return jsonify({
            'success': True,
            'data': {
                'records': records,
                'pagination': {
                    'page': page,
                    'per_page': per_page,
                    'total': pagination.total,
                    'pages': pagination.pages,
                    'has_next': pagination.has_next,
                    'has_prev': pagination.has_prev
                }
            },
            'message': '获取干预记录成功'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取干预记录失败: {str(e)}'
        }), 500


@miniprogram_bp.route('/query/summary', methods=['GET'])
@jwt_required()
def get_data_summary():
    """
    获取数据汇总信息
    """
    try:
        current_user_id = get_jwt_identity()
        # JWT identity是字符串，需要转换为整数
        user = User.query.get(int(current_user_id))
        
        if not user or not user.student_id:
            return jsonify({
                'success': False,
                'message': '用户未绑定学生'
            }), 400
        
        student_id = user.student_id
        
        # 统计视力记录
        vision_count = VisionRecord.query.filter_by(student_id=student_id).count()
        latest_vision = VisionRecord.query.filter_by(student_id=student_id).order_by(
            desc(VisionRecord.measure_date)
        ).first()
        
        # 统计干预记录
        intervention_count = InterventionRecord.query.filter_by(student_id=student_id).count()
        home_intervention_count = InterventionRecord.query.filter_by(
            student_id=student_id, 
            is_home_intervention=True
        ).count()
        
        # 最新干预记录
        latest_intervention = InterventionRecord.query.filter_by(
            student_id=student_id
        ).order_by(desc(InterventionRecord.intervention_date)).first()
        
        # 保留分组结构，同时增加前端当前 WXML 使用的扁平字段，避免页面为空
        summary_data = {
            'student_id': student_id,
            # 原结构
            'vision_records': {
                'total_count': vision_count,
                'latest_record': {
                    'date': latest_vision.measure_date.isoformat() if latest_vision else None,
                    'left_eye_naked': latest_vision.left_eye_naked if latest_vision else None,
                    'right_eye_naked': latest_vision.right_eye_naked if latest_vision else None,
                    'vision_level': latest_vision.vision_level if latest_vision else None
                } if latest_vision else None
            },
            'intervention_records': {
                'total_count': intervention_count,
                'home_intervention_count': home_intervention_count,
                'latest_record': {
                    'date': latest_intervention.intervention_date.isoformat() if latest_intervention else None,
                    'type': latest_intervention.intervention_type if latest_intervention else None,
                    'is_home': latest_intervention.is_home_intervention if latest_intervention else None
                } if latest_intervention else None
            },
            # 扁平兼容字段（前端 query.wxml 中使用 vision_count / intervention_count 等）
            'vision_count': vision_count,
            'latest_vision_level': latest_vision.vision_level if latest_vision else None,
            'vision_trend': None,  # TODO: 后续实现趋势分析
            'intervention_count': intervention_count,
            'home_intervention_count': home_intervention_count,
            'avg_effectiveness': None  # TODO: 统计平均 daily_effect_rating
        }
        
        return jsonify({
            'success': True,
            'data': summary_data,
            'message': '获取数据汇总成功'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取数据汇总失败: {str(e)}'
        }), 500